package org.steven.crm.core.service.indexnumber;

import org.steven.crm.core.service.BaseService;
import com.steven.xdb.dbmanager.DBManager;
import com.steven.xdb.pagination.query.AbstractQueryDataList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/1/11 22:19
 * @Version 1.0
 */
public class IndexNumberService extends BaseService {
    @Override
    protected String getTable() {
        return "indexnumbers";
    }

    @Override
    protected AbstractQueryDataList getQueryDataList() {
        return null;
    }

    @Override
    protected String getDataSourceName() {
        return null;
    }

    public String getIndexNumber(String tableName) throws Exception {
        String sql = "select * from " + getTable() + " where tableName = ? for update";
        List<String> p = new ArrayList<>();
        p.add(tableName);

        List<Map<String, String>> datas = DBManager.query(getSession(), sql, p);
        if (datas.size() == 0) {
            Map<String, String> kv = new HashMap<>();
            kv.put("tableName", tableName);
            kv.put("indexNumber", "1");
            DBManager.insert(getSession(), getTable(), kv);
            return "1";
        } else {
            String newIndexNumber = (Long.parseLong(datas.get(0).get("indexNumber")) + 1) + "";
            Map<String, String> k = new HashMap<>();
            k.put("tableName", tableName);
            Map<String, String> v = new HashMap<>();
            v.put("indexNumber", newIndexNumber);
            DBManager.update(getSession(), getTable(), k, v);
            return newIndexNumber;
        }
    }
}
